package com.shujia.flink.core

import org.apache.flink.api.common.functions.MapFunction
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend
import org.apache.flink.streaming.api.CheckpointingMode
import org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup
import org.apache.flink.streaming.api.scala._

import scala.collection.mutable

object Demo11HashMap {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment


    /**
     * 打开flink的checkpoint
     *
     */

    // 每 1000ms 开始一次 checkpoint
    env.enableCheckpointing(1000)
    // 高级选项：
    // 设置模式为精确一次 (这是默认值)
    env.getCheckpointConfig.setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE)

    // 确认 checkpoints 之间的时间会进行 500 ms
    env.getCheckpointConfig.setMinPauseBetweenCheckpoints(500)

    // Checkpoint 必须在一分钟内完成，否则就会被抛弃
    env.getCheckpointConfig.setCheckpointTimeout(60000)

    // 允许两个连续的 checkpoint 错误
    env.getCheckpointConfig.setTolerableCheckpointFailureNumber(2)

    // 同一时间只允许一个 checkpoint 进行
    env.getCheckpointConfig.setMaxConcurrentCheckpoints(1)

    // 使用 externalized checkpoints，这样 checkpoint 在作业取消后仍就会被保留
    //RETAIN_ON_CANCELLATION: 当任务取消时保留checkpoint
    env.getCheckpointConfig.setExternalizedCheckpointCleanup(
      ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION)
    /**
     * 需要设置flink checkpoint保存状态的位置
     *
     */

    env.setStateBackend(new HashMapStateBackend())
    //将状态保存到hdfs中
    env.getCheckpointConfig.setCheckpointStorage("hdfs://master:9000/flink/checkpoint")




    val linesDS: DataStream[String] = env.socketTextStream("master", 8888)

    val wordsDS: DataStream[String] = linesDS.flatMap(_.split('<'))

    val keyByDS: KeyedStream[String, String] = wordsDS.keyBy(wrod => wrod)

    val countDS: DataStream[(String, Int)] = keyByDS.map(new MapFunction[String, (String, Int)] {
      /**
       * 同于保存单词的数量（状态）
       *
       * 使用一个普通的结果保存之前的计算结果，如果任务执行失败，集合中保存的结果会丢失
       *
       */
      private val wordCount = new mutable.HashMap[String, Int]()

      override def map(word: String): (String, Int) = {
        //如果map集合中有就获取让后累加，再更新，
        var count: Int = wordCount.getOrElse(word, 0)
        //累加
        count += 1
        //更新
        wordCount.put(word, count)

        //返回新的单词的数量
        (word, count)
      }
    })

    countDS.print()

    env.execute()
  }

}
